<?php

namespace App\Jobs;

use App\Constant\QueueKey;
use App\Constant\NewFlowEnum;
use App\Constants\RedisKey;
use App\Events\NewFlowOrderEvent;
use App\Facades\RiskPlatformRequestFacade;
use App\Models\UserApplyRiskLog;
use App\Models\UserAuthSpiderTransLog;
use App\Models\UserDeviceInfo;
use App\Models\UserLoanRequest;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

class CheckSpiderJob implements ShouldQueue {
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public $tries = 3;

    public $timeout = 30;

    protected $tran;

    /**
     * Create a new job instance.
     *
     * @param UserAuthSpiderTransLog $tran
     */
    public function __construct(UserAuthSpiderTransLog $tran) {
        $this->tran = $tran;
        $this->onQueue(QueueKey::QUEUE_RISK_SPIDER_STATUS);
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle() {
        $tran = $this->tran;
        $key = sprintf(RedisKey::RISK_COMMIT_LOCK,$tran->user_id);
        $lock = Redis::get($key);
        \Log::debug('进入申请风控,锁状态'.(string)$lock);
        if(!$lock){
            Redis::setex($key,5,1);
            try {
                \DB::beginTransaction();
                $flag = UserApplyRiskLog::where('loan_request_id', $tran->loan_request_id)->count();
                if (!$flag) {
                    $device = UserDeviceInfo::byLoanId($tran->loan_request_id)->first();
                    $params = [
                        'device_id'   => $device->risk_device_id,
                        'device_type' => $device->risk_device_type,
                    ];
                    //condition 待申请 用户ID
                    $loan = UserLoanRequest::with(['user', 'phone', 'bankCard', 'baseInfo', 'userCert', 'userTransLog'])->find($tran->loan_request_id);
                    $data = RiskPlatformRequestFacade::createParams($loan, $loan->user, $params);
                    $ret  = RiskPlatformRequestFacade::useRiskSystem($data);

                    \Log::debug('申请风控返回结果:' . json_encode($ret, JSON_UNESCAPED_UNICODE));
                    Log::debug("NewFlowOrderEvent NewFlowRiskInit-loanid:" . $tran->loan_request_id);
                    event(new NewFlowOrderEvent(NewFlowEnum::NewFlowRiskInit, false, $tran->loan_request_id));
                    if ($ret['code'] == '01') {
                        $riskId = $ret['data']['riskId'];
                        //记录风控信息
                        UserApplyRiskLog::create([
                            'loan_request_id' => $tran->loan_request_id,
                            'risk_id' => $riskId
                        ]);
                        \Log::debug('风控入库成功！');
                    } else {
                        throw new \Exception('风控状态不为01' . json_encode($ret, JSON_UNESCAPED_UNICODE));
                    }
                }
                \DB::commit();
            } catch (\Exception $e) {
                \DB::rollBack();
                UserAuthSpiderTransLog::handleByStatus($tran->loan_request_id);
                \Log::debug('风控异常:' . $e->getMessage());
            }
        }
    }
}
